package com.taxis.common;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class EncryptText {

	public EncryptText() { }

	public String encrypt(String text) {
		MessageDigest algorithm = null;

		try {
			algorithm = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException nsae) {
			System.out.println("Cannot find digest algorithm");
		}

		byte[] defaultBytes = text.getBytes();
		algorithm.reset();
		algorithm.update(defaultBytes);
		byte messageDigest[] = algorithm.digest();
		StringBuffer hexString = new StringBuffer();

		for (int i=0; i<messageDigest.length; i++) {
			String hex = Integer.toHexString(0xFF & messageDigest[i]);
			if (hex.length() == 1) {
				hexString.append('0');
			}
			hexString.append(hex);
		}
		return hexString.toString();
	}
}

/*
The following code works well if you only need to print the digest value:

for (byte b : md.digest())
System.out.printf("%02x", 0xFF&b);
-----------------------------------------------------------
Please note that if you are using MD5 for authentication means, you really consider using
a salt alongside the value you wish to create an md5 of to increase security. 
Better to use SHA-256 although you need to use more characters in your database password table.

algorithm = MessageDigest.getInstance("SHA-256");

g@h ~/bin$ java -cp . test.MD5Test "bark at the moon"  
SHA-256 ("bark at the moon") = a5bb786220762b74c9569cd9f150a4176f9da3c2ac29d776a65487b2a77d4429

-----------------------------------------------------------
You can use BigInteger to do the byte array conversion....

    static String getMd5Digest(String input)
        {
            try
            {
                MessageDigest md = MessageDigest.getInstance("MD5");
                byte[] messageDigest = md.digest(input.getBytes());
                BigInteger number = new BigInteger(1,messageDigest);
                return number.toString(16);
            }
            catch(NoSuchAlgorithmException e)
            {
                throw new RuntimeException(e);
            }
        }
*/